package com.ky.pro.java.concurrency;

import com.ky.pro.java.concurrency.algo.FiboUtil;

import java.util.concurrent.Semaphore;

/**
 * @ClassName SemaphoreMain
 * @Description 使用信号量实现
 * @Date 2021/11/27 8:56
 * @Author kevin
 **/
public class SemaphoreMain {

    public static void main(String[] args) {
        long start = System.currentTimeMillis();

        // 在这里创建一个线程或线程池，
        // 异步执行 下面方法

        Semaphore semaphore = new Semaphore(0, true);

        FiboSemaphoreTask fiboTask = new FiboSemaphoreTask(semaphore);

        new Thread(fiboTask).run();
        int result = fiboTask.getResult();
        // 确保  拿到result 并输出
        System.out.println("异步计算结果为：" + result);

        System.out.println("使用时间：" + (System.currentTimeMillis() - start) + " ms");

        // 然后退出main线程
    }

    static class FiboSemaphoreTask implements Runnable {

        private Semaphore semaphore;
        private int result;

        public FiboSemaphoreTask(Semaphore semaphore) {
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            result = FiboUtil.fibo(36);
            semaphore.release();
        }

        public int getResult() {
            try {
                semaphore.acquireUninterruptibly();
                System.out.println("获取结果准入线程：" + Thread.currentThread().getName());
                return result;
            } finally {
                semaphore.release();
            }
        }

    }

}
